<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>云校通-教师-学生常规登记</title>
<jsp:include page="/WEB-INF/page/common/_header.jsp"></jsp:include>
<script src="<%=basePath %>/js/picker.js"></script>
<script src="<%=basePath %>/js/select.js"></script>
<body ontouchstart class="js-jf">
	<div class="weui_tab tab-bottom">
		<div class="weui_tab_bd">
			<div class="weui-header bg-blue"> 
		  		<div class="weui-header-left"> <a href="<%=basePath %>/ls/student/points/" class="icon icon-109 f-white">返回</a > </div>
		    	<h1 class="weui-header-title">学生常规登记</h1>
		  	</div>
			<div class="weui_cells weui_cells_access mt0">
				<div class="weui_cell">
			        <div class="weui_cell_hd">
			          	<label class="weui_label">加减分选择</label>
			        </div>
         		  	<div class="weui_cell_bd weui_cell_primary">
						<input id="scoreType" class="weui_input tr" value="减分" type="text" data-values="0"/>
	      			</div>
	      			<div class="weui_cell_ft"></div>
	    		</div>
	    	</div>
			<div class="weui_cells weui_cells_access">
				<div class="weui_cell">
			        <div class="weui_cell_hd">
			            <label class="weui_label label3">被评分对象</label>
			        </div>
			        <div class="weui_cell_bd weui_cell_primary">
						<input type="text" id="targetType" class="weui_input weui_input-select tr main1" value="请选择" readonly="readonly"/>
			        </div>
			        <div class="weui_cell_ft"></div>
		        </div>
				<div class="weui_cell">
			        <div class="weui_cell_hd">
			            <label class="weui_label label3">被评分人</label>
			        </div>
			        <div class="weui_cell_bd weui_cell_primary">
						<input type="text" id="regTeacher" class="weui_input weui_input-select tr main1" value="请选择" readonly="readonly"/>
			        </div>
			        <div class="weui_cell_ft"></div>
		        </div>
		        <div class="weui_cell">
		            <div class="weui_cell_hd">
		             	<label class="weui_label label3">评价部门</label>
		            </div>
		            <div class="weui_cell_bd weui_cell_primary">
		  				<input type="text" id="judgeDepart" class="weui_input weui_input-select tr main1" value="请选择" readonly="readonly"/>
		            </div>
		            <div class="weui_cell_ft"></div>
  	      		</div>
  				<div class="weui_cell" id="zBtn">
		            <div class="weui_cell_hd">
		             	<label class="weui_label label3">评价类别</label>
		            </div>
		            <div class="weui_cell_bd weui_cell_primary" id="typeInput">
		  				<input type="text" id="judgeType" class="weui_input weui_input-select tr main1" value="请选择" readonly="readonly"/>
		            </div>
		            <div class="weui_cell_ft"></div>
  	      		</div>
				<div class="weui_cell  weui_select_after">
					<div class="weui_cell_hd">
						<label class="weui_label">评价内容</label>
					</div>
		        </div>
 	      		<div class="weui_cell">
	                <div class="weui_cell_bd weui_cell_primary">
	                    <textarea id="judgeContent" name="judgeContent" class="weui_textarea" placeholder="请详细描述评价内容" rows="3"></textarea>
	                </div>
	            </div>
	            <div class="weui_uploader">
                    <div class="weui_uploader_bd">
                        <ul class="weui_uploader_files img-click" id="img1">
                        </ul>
                        <div class="weui_uploader_input_wrp" id="filePicker" style="margin-bottom: 20px; margin-left: 15px; width: 60px; height: 60px; border-radius: 5px;">
                            <input class="weui_uploader_input" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" id="imgid"/>
                        </div>
                    </div>
	            </div>
  	      	</div>
  	      	<div class="weui_btn_area">
	      		<a href="javascript:" onclick="regSubmit()" class="weui_btn bg-blue">确认提交</a>
	    	</div>  
		</div>
	</div>
	
	<div class="hide_bd1"></div>
	<div class="hb_choose type1">
		<h1>选择评分对象</h1>   
		<div class="searchbar_wrap"></div>
		<div class="name_show">
			<ul></ul>
		</div>
		<div class="name_show_box">
			<ul>
			</ul>
		</div>
		<div class="bg_white last_li">
			<strong><b class="cancel">取消</b></strong>
			<strong><b class="bg-blue f-white make">确认</b></strong>
	    </div>
	</div>
	<div class="hb_choose type2" style="top: 154px;width: 100%;left:0;">
		<div class="bj">
			
		</div>
      	<div class="bg_white1">
			<p>班级:<span id="teachers">0</span></p>
			<b class="bg-blue f-white make">确认</b>
      	</div>
	</div>
	
</body>
<jsp:include page="/WEB-INF/page/common/_footer.jsp"></jsp:include>
<script type="text/javascript">
	var typeData, search=false;
	$(function() {
		$('.searchbar_wrap').searchBar({
	        cancelText:"取消",
	        searchText:'请输入评分对象',
	        onfocus: function (value) {
	           $('.name_show_box').show();
	        },
	        onblur:function(value) {
	        		
	        },
	        input: function(value) {
	        	queryItem(value);
	        },
	        onsubmit:function(value){
	        	queryItem(value);
	        },
	        oncancel:function(){
	        	$('.name_show_box ul').html('');
	        	$('.name_show_box').hide();
	        },
	        onclear:function(){
	        	$('.name_show_box ul').html('');
	        	$('.name_show_box').hide();
	        }
	    });
		$("#scoreType").select({
	        items: [
               {title: "加分", value: 1,},
	           {title: "减分", value: 0,}
	        ]
	   	});
		$("#targetType").select({
			items: [
			   {title: "班级", value: 1},
			   {title: "学生", value: 2}
			],
			onChange: function(d) {
		       $(".make").trigger("click");
		    }
		});
		$("#regTeacher").click(function() {
			var targetType = $("#targetType").attr("data-values");
			if(targetType) {
				if(targetType == 1) {
					$(".type2").show();
					$(".hide_bd1").attr("style", "display: block;");
				}else if(targetType == 2) {
					$(".type1").show();
					$(".hide_bd1").attr("style", "display: block;");
				}
			}
		})
		$(".make").click(function() {
			var targetType = $("#targetType").attr("data-values");
			if(targetType == 1) {
				$(".type2").hide();
				$(".hide_bd1").attr("style", "display: none;");
				var len = $(".list_3 input:checked").length;
				if(len == 0) {
					$("#regTeacher").val("请选择");
				}else {
					$("#regTeacher").val("已选择"+ len +"个班级");
				}
			}else if(targetType == 2) {
				$(".type1").hide();
				$(".hide_bd1").attr("style", "display: none;");
				var len = $(".name_show li").length;
				if(len == 0) {
					$("#regTeacher").val("请选择");
				}else {
					$("#regTeacher").val("已选择"+ len +"个学生");
				}
			}
		})
		$(".cancel").click(function() {
			$(".type2").hide();
			$(".type1").hide();
			$(".hide_bd1").attr("style", "display: none;");
		})
		$(document).on("click", ".hb_choose .title>li", function(e) {
			$(this).addClass("active").siblings().removeClass("active");
			$(".yng").hide();
			$("#" + $(this).attr("data-key")).show();
    	});
		$(document).on("change", ".list_3 input", function(e) {
			$("#teachers").html($(".list_3 input:checked").length);
		});
    	
		loadTeacher();
		loadPower();
	})
	function listDel(thiz) {
    	$(thiz).remove();
    }
	function searchPoint(thiz){
    	var teacherId = $(thiz).attr("data-id");
    	var teacherName = $(thiz).attr("data-name");
    	$('.name_show_box ul').html('');
    	$('.name_show_box').hide();
    	$("#weui_search_input").val(null);
   		$('.name_show').find('ul').append('<li onclick="listDel(this)" class="list-del" data-id="'+teacherId+'" data-name="'+teacherName+'">'+teacherName+'<span class="list-del-vaild"></span></li>');
    }
	function loadPower() {
		$.ajax({
    		url: basePath + "/ls/student/points/register/power",
    		type: 'POST',
    		dataType : "json",
    		success: function(data) {
    			if(data != null) {
    				typeData = data;
    				loadDepart();
    			}
    		},
    		error: function(data) {
    			alert("系统异常,请联系管理员");
    		}
    	});
	}
	function loadDepart() {
		if(typeData.length == 1) {
			$("#judgeDepart").val(typeData[0].depart);
			$("#judgeDepart").attr("data-values", typeData[0].id);
			loadType(typeData[0].id);
		}else {
			var items = [];
			for(var i in typeData) {
				items.push({title: typeData[i].depart, value: typeData[i].id});
			}
			$("#judgeDepart").select({
		        items: items,
		        onChange: function(d) {
		            loadType(d.values);
		        }
		   	});
		}
	}
	function loadType(departId) {
		var data;
		for(var i in typeData) {
			if(typeData[i].id == departId) {
				data = typeData[i];
				break;
			}
		}
		var routineType = data.routineType;
		var routineTypeScore = data.routineTypeScore;
		var items = [];
		var routineTypes = routineType.split(",");
		var routineTypeScores = routineTypeScore.split(",");
		for(var i in routineTypes) {
			var title = routineTypes[i] + " " + routineTypeScores[i]+"分";
			var value = routineTypes[i] + "-" + routineTypeScores[i];
			items.push({title: title, value: value})
		}
		$("#judgeType").remove();
		$("#typeInput").html('<input type="text" id="judgeType" class="weui_input weui_input-select tr main1" value="请选择" readonly="readonly"/>');
		$("#judgeType").select({
	        items: items
	   	});
	}
	function loadTeacher() {
		$.ajax({
    		url: basePath + "/classList",
    		type: 'POST',
    		dataType : "json",
    		success: function(data) {
    			if(data != null) {
    				var html = '<ul class="title">';
    				for(var i in data) {
    					var itm = data[i];
    					html += '<li class="'+(i == 0 ? "active " : "")+'" data-key="s'+itm.grade+'">'+itm.gradeText+'</li>';
    				}
    				html += "</ul>";
    				for(var i in data) {
    					var itm = data[i];
    					html += '<div class="yng" id="s'+itm.grade+'"><ul class="list_3">';
    					for(var j in itm.classList) {
    						var itm1 = itm.classList[j];
    						var gradeClass = itm1.grade + (itm1.clazz < 10 ? "0" : "")+itm1.clazz;
    						html += '<li><div class="weui_cell_hd list_c3">\
								<label class="weui_cells_checkbox weui_check_label" for="'+gradeClass+'">\
								<input type="checkbox" class="weui_check" value="'+gradeClass+'" id="'+gradeClass+'">\
	    						<i class="weui_icon_checked"></i>\
	    						</label>'+itm1.clazz+'班\
							</div></li>';
    					}
    					html += '</ul></div>';
    				}
    				$(".bj").html(html);
    				$("#s" + data[0].grade).show();
    			}
    		},
    		error: function(data) {
    			alert("系统异常,请联系管理员");
    		}
    	});
	}
	function queryItem(keyword) {
		if(!/^[\u4E00-\u9FA5]+$/.test(keyword)) return;
		if(search) return;
		search = true;
		$.ajax({
    		url: basePath + "/ls/students/manage/keyword1",
    		type: 'POST',
    		dataType : "json",
    		data: {
    			studentName: keyword
    		},
    		success: function(data) {
    			search = false;
    			if (data != null && data.length > 0) {
    				var html = "";
    				for(var i in data) {
    					var itm = data[i];
    					html += "<li onclick='searchPoint(this)' data-id="+itm.id+" data-name="+itm.name+">"+itm.name+"</li>";
    				}
    				$(".name_show_box ul").html(html);
    			}
    		},
    		error: function(data) {
    			alert("系统异常,请联系管理员");
    		}
    	});
	}
	function regSubmit() {
		var scoreType = $("#scoreType").attr("data-values");
		if(emptyToNull(scoreType) == null) {
			$.alert("请选择加减法","");
			return;
		}
		var judgeDepart = $("#judgeDepart").val();
		if(emptyToNull(judgeDepart) == null) {
			$.alert("请选择评价部门","");
			return;
		}
		var type = $("#judgeType").attr("data-values");
		if(emptyToNull(type) == null) {
			$.alert("请选择评价类别","");
			return;
		}
		var targetType = $("#targetType").attr("data-values");
		if(emptyToNull(targetType) == null) {
			$.alert("请选择被评价对象","");
			return;
		}
		var len = 0;
		var targetIds = "";
		if(targetType == 1) {
			len = $(".list_3").find("input:checked").length;
			if(len > 0) {
				$(".list_3").find("input:checked").each(function(i,v){
					targetIds += $(v).val() + ((i+1) < len ? "," : "");
				});
			}
		}else if(targetType == 2) {
			len = $(".name_show li").length;
			if(len > 0) {
				$(".name_show li").each(function(i,v){
					targetIds += $(v).attr("data-id") + ((i+1) < len ? "," : "");
				});
			}
		}
		if(len == 0) {
			$.alert("请选择被评人","");
			return;
		}
		var attachIds = "";
		$("#img1").find("li").each(function(i,v){
			attachIds += $(v).attr("data-id") + ((i+1) < $("#img1").find("li").length ? "," : "");
		});
		var typeArray = type.split("-");
		var judgeType = typeArray[0];
		var score = typeArray[1];
		var judgeContent = $("#judgeContent").val();
		$.ajax({
    		url: basePath + "/ls/student/points/register/submit",
    		type: 'POST',
    		dataType : "json",
    		data: {
    			scoreType: scoreType,
    			judgeDepart: judgeDepart,
    			judgeType: judgeType,
    			score: score,
    			judgeContent: judgeContent,
    			attachIds: attachIds,
    			targetIds: targetIds,
    			targetType: targetType
    		},
    		success: function(data) {
    			if(data.code == '000') {
    				$.toast("提交成功");
    				setTimeout(function(){window.location.href = window.location.href + "?v="+new Date().getTime();}, 1000);
    			}else {
    				$.toast(data.msg, "cancel");
    			}
    		},
    		error: function(data) {
    			alert("系统异常,请联系管理员");
    		}
    	});
	}
	
	document.querySelector('#imgid').onchange = function(e) {
		var files = e.target.files;
		var len = files.length;
		for (var i=0; i < len; i++) {
			lrz(files[i], {
				width:1080
			})
			.then(function (rst) {
				var xhr = new XMLHttpRequest();
	            xhr.open('POST', basePath + "/ls/attchment/upload/lrz");
	            xhr.onload = function () {
	                if (xhr.status === 200) {
	                	var obj = JSON.parse(xhr.response)
	                	$("#img1").append('<li class="weui_uploader_file" data-id="'+obj.data.id+'" style="margin-right:0;margin-bottom:10px;position: relative;"><div class="img-del" onclick="imgDel(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ rst.base64 +'"/></li>')
	                }
	            };
	            xhr.onerror = function () {
	            	alert("上传异常");
	            };
	            xhr.upload.onprogress = function (e) {
	                // 上传进度
	                var percentComplete = ((e.loaded / e.total) || 0) * 100;
	            };
	            // 添加参数
	            rst.formData.append('attachmentName', rst.origin.name);
	            rst.formData.append('attachmentSize', rst.fileLen);
	            rst.formData.append('baseData', rst.base64);
	            rst.formData.append('attachmentType', "image");
	            rst.formData.append('relationType', "studentRoutine");
	            // 触发上传
	            xhr.send(rst.formData);
	            return rst;
			})
	        .always(function () {
	            // 不管是成功失败，都会执行
	        });
			;
		}
	}

	//拍照或从手机相册中选图接口
	$('#filePicker').on('click', function () {
		wx.chooseImage({
		    count: 9,
		    needResult: 1,
		    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
		    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		    success: function (res) {
		   		var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
		   		wxuploadImage(localIds);
		    },
		    fail: function (res) {
		        alterShowMessage("操作提示", JSON.stringify(res), "1", "确定", "", "", "");
		    }
		
		});
	});
	function wxuploadImage(localIds) {  
		var localId = localIds.pop();
		wx.uploadImage({  
		    localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得  
		    isShowProgressTips: 1, // 默认为1，显示进度提示  
		    success: function (res) {  
		        mediaId = res.serverId; // 返回图片的服务器端ID
		        wechatMediaDownload(mediaId);
		        if(localIds.length > 0){
		        	wxuploadImage(localIds);
		        }
		    },  
		    fail: function (error) {  
		        alert(Json.stringify(error));  
		    }  
		});
	}  
	function wechatMediaDownload(mediaId) {
		var params = {};
		params.mediaId = mediaId;
		params.attachmentType = "image";
		params.relationType = "studentRoutine";
		$.ajax({
			url : basePath + "/ls/attchment/upload/wx",
			type : "post",
			data : params,
			dataType : "json",
			async : false,
			success : function(data) {
				if(data.code != '000') {
					$.toast(data.msg, "cancel");
				}else {
					$('#img1').append('<li class="weui_uploader_file" data-id="'+data.data.id+'" style="margin-right:0;margin-bottom:16px;position: relative;"><div class="img-del" onclick="imgDel(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ imgUrl + data.data.attachmentUrl +'"/></li>'); 
				}
			}, error:function(){
				alert("上传异常");
				}
		});
	}
</script>
</html>